package com.bai.process.service.impl;


import com.bai.model.process.ProcessTemplate;
import com.bai.model.process.ProcessType;
import com.bai.process.mapper.OaProcessTemplateMapper;
import com.bai.process.mapper.OaProcessTypeMapper;
import com.bai.process.service.OaProcessService;
import com.bai.process.service.OaProcessTemplateService;
import com.bai.process.service.OaProcessTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author bai
 * @since 2023-05-27
 */
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate> implements OaProcessTemplateService {

    @Autowired
    private OaProcessTypeService processTypeService;
    @Autowired
    private OaProcessService processService;

    @Override
    public IPage<ProcessTemplate> selectPageProcessTempate(Page<ProcessTemplate> pageParam) {
        //调用mapper的方法实现分页查询
        Page<ProcessTemplate> templatePage = baseMapper.selectPage(pageParam, null);
        //从分页数据中获取列表list集合
        List<ProcessTemplate> records = templatePage.getRecords();
        //便利list集合，得到每个对象的审批id
        for (ProcessTemplate record : records) {
            Long processTypeId = record.getId();
            //根据审批类型id，查询获取对应名称
            LambdaQueryWrapper<ProcessType> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProcessType::getId, processTypeId);
            ProcessType processType = processTypeService.getOne(queryWrapper);
            if (processType == null) {
                continue;
            }
            //封装
            record.setProcessTypeName(processType.getName());
        }
        return templatePage;
    }

    @Override
    public void publish(Long id) {
        //TODO:修改模板发布状态
        ProcessTemplate processTemplate = baseMapper.selectById(id);
        processTemplate.setStatus(1);
        baseMapper.updateById(processTemplate);
        //TODO:流程定义部署
         if (!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
             processService.deployByZip(processTemplate.getProcessDefinitionPath());
         }
    }
}
